﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace MWS_Main
{
    public partial class imageProcesor : System.Web.UI.Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if ( Request.QueryString["urlImagen"] != null )
            {
                WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
                string urlImagen=Request.QueryString["urlImagen"];
                if ( System.IO.File.Exists( config.Settings["sitePath"].value + urlImagen ) )
                {
                    if ( Request.QueryString["imageSize"] != null )
                    {
                        int anchoImagen=0;
                        WLMCoreLibrary.WLMFunctions.TryParseToInt( Request.QueryString["imageSize"], out anchoImagen );
                        string urlThumb=config.Settings["thumbsPath"].value + anchoImagen + "px/" + urlImagen.Replace( config.Settings["imagePath"].value, "" ).Replace( "/", "" );
                        if ( System.IO.File.Exists( config.Settings["sitePath"].value + urlThumb ) )
                        {
                            Response.Redirect( urlThumb );
                        }
                        else
                        {
                            ResizeImage( config.Settings["sitePath"].value + urlImagen, urlImagen.Replace( config.Settings["imagePath"].value, "" ).Replace( "/", "" ), config.Settings["sitePath"].value + config.Settings["thumbsPath"].value + anchoImagen + "px/", anchoImagen );
                            Response.Redirect( urlThumb );
                        }
                    }
                    else
                        Response.Redirect( urlImagen );
                }
            }
        }

        //public string GetThumbNail(int thumbSize)
        //{
        //    try
        //    {
        //        WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
        //        string path1 = config.Settings["sitePath"].value;
        //        string nuevoNombreArchivo = _archivo.Split('.')[0] + "_" + thumbSize.ToString() + "." + _archivo.Split('.')[1];
        //        if (!File.Exists(path1 + config.Settings["thumbsPath"].value + nuevoNombreArchivo))
        //        {
        //            FileStream lecto = new FileStream(path1 + config.Settings["imagePath"].value + fechaCreacion.Year + "/" + fechaCreacion.Month + "/" + fechaCreacion.Day + "/" + _archivo, FileMode.Open);

        //            ResizeImage(lecto, nuevoNombreArchivo, config.Settings["thumbsPath"].value, thumbSize);
        //            lecto.Close();

        //        }
        //        return config.Settings["thumbsPath"].value + nuevoNombreArchivo;
        //    }
        //    catch { return ""; }

        //}

        private void ResizeImage( string sourceFile, string fileName, string directoryName, int imageWidthResize )
        {
            System.IO.DirectoryInfo directorio = new System.IO.DirectoryInfo( directoryName );
            if ( !directorio.Exists )
                directorio.Create();
            FileStream streamFile = new FileStream( sourceFile, FileMode.Open, FileAccess.Read );
            Bitmap bmp1 = new Bitmap( streamFile );

            //Or you do can use buil-in method
            //ImageCodecInfo jgpEncoder GetEncoderInfo("image/gif");//"image/jpeg",...
            ImageCodecInfo jgpEncoder = GetEncoder( ImageFormat.Jpeg );

            // Create an Encoder object based on the GUID
            // for the Quality parameter category.
            System.Drawing.Imaging.Encoder myEncoder =
            System.Drawing.Imaging.Encoder.Quality;

            // Create an EncoderParameters object.
            // An EncoderParameters object has an array of EncoderParameter
            // objects. In this case, there is only one
            // EncoderParameter object in the array.
            EncoderParameters myEncoderParameters = new EncoderParameters( 1 );

            EncoderParameter myEncoderParameter = new EncoderParameter( myEncoder, 78L );
            myEncoderParameters.Param[0] = myEncoderParameter;

            if ( bmp1.Width > imageWidthResize )
            {
                if ( fileName.Split( '.' )[fileName.Split( '.' ).Length - 1] == "gif" )
                {
                    jgpEncoder = GetEncoder( ImageFormat.Gif );
                }
                if ( fileName.Split( '.' )[fileName.Split( '.' ).Length - 1] == "png" )
                {
                    jgpEncoder = GetEncoder( ImageFormat.Png );
                }
                int srcWidth = bmp1.Width;
                int srcHeight = bmp1.Height;

                Decimal sizeRatio = ( (Decimal)srcHeight / srcWidth );
                int thumbHeight = Decimal.ToInt32( sizeRatio * imageWidthResize );

                Bitmap bmp = new Bitmap( imageWidthResize, thumbHeight );

                System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage( bmp );

                gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle( 0, 0, imageWidthResize, thumbHeight );
                gr.DrawImage( bmp1, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel );
                bmp.Save( directoryName + fileName, jgpEncoder, myEncoderParameters );
            }
            else
            {
                bmp1.Save( directoryName + fileName, jgpEncoder, myEncoderParameters );
            }
            bmp1.Dispose();

            //File.Delete(ConfigurationManager.AppSettings["sitePath"] + ConfigurationManager.AppSettings["imagesPath"] + _archivo);
            //_archivo = nuevoId0.ToString() + "." + extencion;
            //_tamano = (int)new FileInfo(ConfigurationManager.AppSettings["sitePath"] + directoryName + archivo).Length;
        }

        private ImageCodecInfo GetEncoder( ImageFormat format )
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach ( ImageCodecInfo codec in codecs )
            {
                if ( codec.FormatID == format.Guid )
                {
                    return codec;
                }
            }
            return null;
        }
    }
}